package springmvc.components.view;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cg
 * @date 2023/6/16 16:07
 */
public class ModelAndView {
    //渲染页面的参数类别
    private Map<String, Object> model;
    //需要渲染的页面名
    private String viewName;

    public ModelAndView() {
    }

    public ModelAndView(String viewName) {
        this.viewName = viewName;
        this.model = new HashMap<>();
    }

    public ModelAndView(Map<String, Object> model, String viewName) {
        this.model = model;
        this.viewName = viewName;
    }

    public Map<String, Object> getModel() {
        return model;
    }

    public void setModel(Map<String, Object> model) {
        Map<String, Object> map = new HashMap<>();
        for (String key : model.keySet()) {
            Object o = model.get(key);
            if (o == null || "".equals(o)) continue;
            Class<?> clazz = o.getClass();
            if (clazz.getClassLoader() == null) {
                map.put(key, o);
            }else {
                for (Field declaredField : clazz.getDeclaredFields()) {
                    declaredField.setAccessible(true);
                    String name = declaredField.getName();
                    try {
                        Object value = declaredField.get(o);
                        map.put(key + "." + name, value);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }

                }
            }
        }
        this.model = map;
    }

    public String getViewName() {
        return viewName;
    }

    public void setViewName(String viewName) {
        this.viewName = viewName;
    }
}
